<?php
class PostsController extends AppController {
	public $helpers = array (
			'Html',
			'Form',
			'Session' 
	);
	
	/*
	 * ThanhLD1 - index function
	 * this function load data to index.ctp file
	*/
	public function index() {
		$this->loadModel ( 'User' );
		
		//Load model Post
		$this->loadModel ( 'Post' );
		
		//load database with limit 10 rows
		$posts = $this->Post->find ( 'all', array (
				'conditions' => 'ORDER BY created DESC LIMIT '. 10
		) );
		
		//if no have data in database of post table or have error occur
		if (!$posts) {
			throw new NotFoundException ( __ ( 'No Data In database!' ) );
		}
		
		//Load model Admin
		$this->loadModel ( 'User' );
		
		//Load model Comment
		$this->loadModel('Comment');
		
		//prepair data
		foreach ( $posts as $key => $post ) {
			
			//get review Text to show at homepage
			$textBody = $post ['Post'] ['body'];
			$bodyS = $this->reviewText ( 1000, $textBody );
			$posts[$key] ['Post'] ['body'] = $bodyS;
			
			//get admin username
			$author = $this->User->find ( 'first', array (
					'conditions' => array (
							'User.ID' => $post ['Post'] ['user_id']
					)
			) );
			$posts[$key] ['Post'] ['username'] = $author ['User'] ['username'];
			
			//get number of comment
			$numComment = $this->Comment->find('count', array('conditions' => array('Comment.post_id' => $post['Post']['id'])));
			$posts[$key]['Post']['numComment'] = $numComment;
			
			//created datetime format
			$formatDate = "F j, o";
			$created = $post['Post']['created'];
			$posts[$key]['Post']['created'] = date($formatDate, strtotime("$created"));
			
			//check thumbnail
			$thumbnail = trim($post['Post']['thumbnail']);
			if (empty($thumbnail)){
				$posts[$key]['Post']['thumbnail'] = "/images/no-photo.jpg";
			}
		}
		
		//hungdv get all sidebar list
		$sidebarList = $this->getSidebarList();
		$this->set('sidebarList', $sidebarList);
		
		// prepare data for render view of home (index.ctp)
		$this->set ( 'posts', $posts );
	}
	
	/** repair a mont-year list for sidebar
	 * @return unknown
	 */
	private function getSidebarList() {
		$resultList = $this->Post->find ( 'all', array (
				'fields' => array (
						"concat(EXTRACT(YEAR FROM created), '-', EXTRACT(MONTH FROM created)) as month_year" 
				),
				'order' => array (
						'month_year DESC' 
				),
				'group' => array (
						'month_year' 
				) 
		) );
		
		return 	$resultList;			
	}
	
	/** get list of posts base on month-year of post created day
	 * @param unknown $monthYear
	 */
	public function listByMonth($monthYear) {
		$resultList = $this->Post->find ( 'all', array (
				'contain' => array (
						'Comment'
				),
				'conditions' => array (
						"concat(EXTRACT(YEAR FROM created), '-', EXTRACT(MONTH FROM created))" => $monthYear 
				),
				'order' => array (
						'Post.created DESC' 
				) 
		) );
		
		/* echo '<pre>';
		print_r($resultList);
		echo '</pre>';
		exit; */
		
		$this->loadModel('User');
		foreach($resultList as $key => $post){
			//get admin username
			$author = $this->User->find ( 'first', array (
					'conditions' => array (
							'User.ID' => $post ['Post'] ['user_id']
					)
			) );
			$resultList[$key] ['Post'] ['username'] = $author ['User'] ['username'];
			//check thumbnail			
			$thumbnail = trim($post['Post']['thumbnail']);
			if (empty($thumbnail)){
				$resultList[$key]['Post']['thumbnail'] = "/images/no-photo.jpg";
			}
		}		
		
		// print_r($resultList); exit;
		$this->set ( 'posts', $resultList );	
		$sidebarList = $this->getSidebarList();		
		$this->set('sidebarList', $sidebarList);
	}
	
	/**
	 * @param string $id
	 */
	public function detail($id = null) {		
		
		$detail = $this->Post->find ( 'first', array (
				'contain' => array (
						'Comment' 
				),
				'conditions' => array (
						'Post.id' => $id 
				) 
		)
		 );
		
		if($detail == null){
			$this->Session->setFlash ( 'This post is not exist', 'default', array (
					'class' => 'alert alert-danger'
			) );			
			return $this->redirect ( array (
					'controller' => 'posts',
					'action' => 'index'
			) );
		}
		
		//check if this post is belong to current logined user
		$isAuthor = false;	
		if ($this->Session->check ( 'userLogin' )) {
			$logined = $this->Session->read ( 'userLogin' );
			if($logined['User']['id'] ==  $detail['Post']['user_id']){
				$isAuthor = true;				
			}
		}
		
		//Load model Admin
		$this->loadModel ( 'User' );
		
		//Load model Comment
		//$this->loadModel('Comment');
		
		//prepair data
		//get admin username
		$author = $this->User->find ( 'first', array (
				'conditions' => array (
						'User.ID' => $detail ['Post'] ['user_id']
				)
		) );
		$detail ['Post'] ['username'] = $author ['User'] ['username'];
			
		//get number of comment
		//$numComment = $this->Comment->find('count', array('conditions' => array('Comment.post_id' => $detail['Post']['id'])));
		//$detail['Post']['numComment'] = $numComment;
		
		//created datetime format
		//$formatDate = "F j, o";
		//$created = $detail['Post']['created'];
		//$detail['Post']['created'] = date($formatDate, strtotime("$created"));
		
		$thumbnail = trim($detail['Post']['thumbnail']);
		if (empty($thumbnail)){
			$detail['Post']['thumbnail'] = "/images/no-photo.jpg";
		}
		
		$sidebarList = $this->getSidebarList();		
		$comments = $detail['Comment'];
			
		$this->set('detail', $detail);
		$this->set('comments',$comments);	
		
		$this->set('sidebarList', $sidebarList);
		//check is this user author of this post.
		$this->set('isAuthor', $isAuthor);
	}
	
	/*
	 * ThanhLD1 - process function
	 * This function load more data from current position at home page
	 * set data to process.ctp and return html 
	 *  and append at current data from home page index.ctp
	 * */
	public function process() {
		//Set layout is empty
		$this->layout="";
		
		//Load model Post
		$this->loadModel ( 'Post' );
		
		// get position of list post to countinues loading - ThanhLD1
		if (isset ( $_POST ['start'] ) && ( int ) ($_POST ['start'])) {
			$start = $_POST ['start'];
		} else {
			$start = 10;
		}
		
		//get more data start at current data on homepage index.ctp
		$posts = $this->Post->find ( 'all', array (
				'conditions' => 'ORDER BY created DESC LIMIT ' . $start . ', 10'
		) );
		
		//if no have data in database of post table or have error occur
		if (!$posts) {
			throw new NotFoundException ( __ ( 'No Data In database!' ) );
		}
		
		//Load model Admin
		$this->loadModel ( 'User' );

		//Load model Comment
		$this->loadModel('Comment');
		
		//prepair data
		foreach ( $posts as $key => $post ) {
				
			//get review Text to show at homepage
			$textBody = $post ['Post'] ['body'];
			$bodyS = $this->reviewText ( 1000, $textBody );
			$posts[$key] ['Post'] ['body'] = $bodyS;
				
			//get admin username
			$author = $this->User->find ( 'first', array (
					'conditions' => array (
							'User.ID' => $post ['Post'] ['user_id']
					)
			) );
			$posts[$key] ['Post'] ['username'] = $author ['User'] ['username'];
			

			//get number of comment
			$numComment = $this->Comment->find('count', array('conditions' => array('Comment.post_id' => $post['Post']['id'])));
			$posts[$key]['Post']['numComment'] = $numComment;
				
			//created datetime format
			$formatDate = "F j, o";
			$created = $post['Post']['created'];
			$posts[$key]['Post']['created'] = date($formatDate, strtotime("$created"));
		}
		
		//return value to append current data at homepage index.ctp
		$this->set ( 'posts', $posts );
	}
	
	/*
	 * ThanhLD1 - review text
	 * This function return a string with maxlength had given to review at homepage
	 * */
	// function get text to show review on home page - ThanhLD1
	private function reviewText($maxLength, $html) {
		if (! $html)
			return "";
		// remove all tag html - ThanhLD1
		$result = trim ( strip_tags ( $html ) );
		if (empty ( $result )) {
			$result = "<p style=\"color: red;\">SORRY! NO REVIEW TEXT!</p>";
		}
		// cut string with length is maxLength - ThanhLD1
		if (strlen ( $result ) > $maxLength) {
			$pos = strpos($result, ' ', $maxLength);
			$result = substr ( $result, 0, $pos );
			$result .= "....";
		}
	
		return $result;
	}
	
	public function test($id = null, $slugaaa = null){		
		
		
		print_r($id . ' --- ' . $slugaaa);
		
		exit;		
		
		
	}
}